package com.foogui.primary.consume;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 利用阻塞队列实现生产者-消费者模型
 */
public class ConsumeByBlockingQueueDemo {
    private  static BlockingQueue<Integer> queue=new ArrayBlockingQueue<>(5);

    public static void main(String[] args) {
        ExecutorService es = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 5; i++) {
            es.execute(new Producer());
        }
        for (int i = 0; i < 10; i++) {
            es.execute(new Consumer());
        }
    }

    static class Consumer implements Runnable{

        @Override
        public void run() {

            while (true){
                try {
                    System.out.println("消费者" + Thread.currentThread().getName() + "，消费了数据：" + queue.take());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    static class Producer implements Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    int e = new Random().nextInt();
                    queue.put(e);
                    System.out.println("生产者" + Thread.currentThread().getName() + "，生产了了数据：" + e);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
